﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04.Net8Cache.Application
{
    public class ProductService
    {
        // 4、设置缓存
        private IMemoryCache _Cache { get; set; }
        public ProductService(IMemoryCache cacheOptions)
        {
            _Cache = cacheOptions;
        }

        public List<Product> GetProduct()
        {
            // 5\缓存处理
            _Cache.TryGetValue<List<Product>>("Product", out List<Product> products);
            if (products == null)
            {
                products = new List<Product>();
                products.Add(new Product() { Id = 1, Name = "小米手机" });
                products.Add(new Product() { Id = 2, Name = "小米汽车" });

                MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions();
                memoryCacheEntryOptions.SetSize(1); // 缓存占用数据大小
                _Cache.Set<List<Product>>("Product", products, memoryCacheEntryOptions);
            }


            return products;
        }
    }
}
